import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:meta/meta.dart';

class SQTest {
  static final _VERSION = 1;

  static final _NAME = "app_flutter.db";

  static Database _database;

  static init() async {
    var databasePath = await getDatabasesPath();
    String path = databasePath + _NAME;

    _database = await openDatabase(path,
        version: _VERSION, onCreate: (Database db, int version) async {});
  }

  static isTableExits(String tableName) async {
    await getCurrentDatabase();
    var res = await _database.rawQuery(
        "select * from Sqlit_master where type = 'table' and name = '$tableName'");
    return res != null && res.length > 0;
  }

  static Future<Database> getCurrentDatabase() async {
    if (_database == null) {
      await init();
    }
    return _database;
  }
}

abstract class DbProvider {
  bool isTableExits = false;

  tableSqlString();

  tableName();

  tableBaseString(String name, String columnId) {
    return '''
        create table $name (
        $columnId integer primary key autoincrement,
      ''';
  }

  Future<Database> getDataBase() async {
    return await open();
  }

  @mustCallSuper
  prepare(name, String createSql) async {
    isTableExits = await SQTest.isTableExits(name);
    if (!isTableExits) {
      Database db = await SQTest.getCurrentDatabase();
      return await db.execute(createSql);
    }
  }

  @mustCallSuper
  open() async {
    if (!isTableExits) {
      await prepare(tableName(), tableSqlString());
    }
    return await SQTest.getCurrentDatabase();
  }
}
